﻿// Copyright (c) Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EdmMetadataHelpers;
using System.Data.EntityClient;
using System.Xml.Linq;

namespace EdmMetadataHelperHarness
{
    public partial class eSQLExecutor : Form
    {
        public eSQLExecutor()
        {
            InitializeComponent();
        }
        /// <summary>
        /// Execute the eSQL in the txtESQL textbox and convert the results to a DataTable
        /// and bind those results to the dgResults datagrid.
        /// </summary>
        private void btnExecuteDataTable_Click(object sender, EventArgs e)
        {
            //Prepare the interface
            HideAll();

            using (EntityConnection connection = new EntityConnection("Name=NorthwindEntities"))
            {
                connection.Open();
                using (EntityCommand command = new EntityCommand(txtESQL.Text.Trim(),connection))
                {
                    using (EntityDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
                    {
                        dgResults.DataSource = EdmDataReaderAdapter.LoadTable(reader);
                    }
                }
            }

            //So the results
            dgResults.Visible = true;
        }
        /// <summary>
        /// Execute the eSQL in the txtESQL textbox and convert the results to XML
        /// and show the XML in the txtResults textbox.
        /// </summary>
        private void btnExecuteXML_Click(object sender, EventArgs e)
        {

            HideAll();

            //Get an entity connection
            using (EntityConnection connection = new EntityConnection("Name=NorthwindEntities"))
            {
                connection.Open();
                using (EntityCommand command = new EntityCommand(txtESQL.Text.Trim(), connection))
                {
                    using (EntityDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
                    {
                        txtResults.Text = new XElement("Results", EdmXmlAdapter.GetElements(reader)).ToString();
                    }
                }
            }

            //Now show the XML
            txtResults.Visible = true;

        }
        /// <summary>
        /// Hide all results
        /// </summary>
        private void HideAll()
        {
            txtResults.Visible = false;
            dgResults.Visible = false;
        }
    }
}
